import jwt
from app.config import WEB_TOTOKEN_SAULT,WEB_TOTOKEN_DURATION
from datetime import datetime
import json
from utils import DEBUG,ERROR
from app.service import UserService
from app.utils.exception import SignatureException

AFTER_TEN_HOURS = int(datetime.now().timestamp() + 10 * 60 * 60)

def tokenDecode(token: str, key: str = None):
    data = jwt.decode(token, key=WEB_TOTOKEN_SAULT, algorithms=['HS256'])
    
    if data == None:
        return  None, None
    
    if isinstance(data, dict) == False:
        return None, None
    
    if "exp" not in data.keys():
        return None, None
    
    now = int(datetime.now().timestamp())
    token_exp = data["exp"]
    
    
    # 小于0代表保存登陆状态
    if token_exp < 0:
        return data, None
    
    if token_exp < now:
        return None, None
    
    # 如果在10分钟内
    if token_exp - now < 600:        
        return data, tokenEncode(token)
    
    return data, None

def tokenEncode(payload :dict, exp: int = None) -> str:
    if exp == None:
        exp = AFTER_TEN_HOURS
    payload['exp'] = exp
    print("tokenEncode", payload)
    return jwt.encode(payload, key=WEB_TOTOKEN_SAULT, algorithm='HS256')

def signatureEncode(payload :dict, exp :int, key :str):
    if key == None:
        raise SignatureException("The key is empty!")
    if exp == None:
        exp = AFTER_TEN_HOURS
    payload['exp'] = exp
    return jwt.encode(payload, key=key, algorithm='HS256')

def signatureDecode(signature: str, key: str):
    if key == None:
        raise SignatureException("The key is empty!")
    
    data = jwt.decode(signature, key=key, algorithms=['HS256'])
    
    
    if data == None:
        return  None
    
    if isinstance(data, dict) == False:
        return None
    
    if "exp" not in data.keys():
        return None

    now = datetime.now().timestamp()
    token_exp = data["exp"]
    if token_exp < now:
        return None
    
    return data